package com.ruoyi.project.rate.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.service.DictService;
import com.ruoyi.project.rate.Constants;
import com.ruoyi.project.rate.Utils;
import com.ruoyi.project.rate.domain.Cp;
import com.ruoyi.project.rate.domain.CpDetail;
import com.ruoyi.project.rate.domain.Kh;
import com.ruoyi.project.rate.domain.KhRule;
import com.ruoyi.project.rate.domain.KhzDept;
import com.ruoyi.project.rate.domain.Result;
import com.ruoyi.project.rate.domain.Scene;
import com.ruoyi.project.rate.domain.Sup;
import com.ruoyi.project.rate.service.CpDetailService;
import com.ruoyi.project.rate.service.KhRuleService;
import com.ruoyi.project.rate.service.KhService;
import com.ruoyi.project.rate.service.KhzDeptService;
import com.ruoyi.project.rate.service.ResultService;
import com.ruoyi.project.rate.service.SceneService;
import com.ruoyi.project.rate.service.SupService;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dict.domain.DictData;

@Controller
@RequestMapping("/rate/result")
public class ResultController extends BaseController {
	private static final BigDecimal ZERO = new BigDecimal("0");
//	private static final BigDecimal ONE = new BigDecimal("1");
	private static final BigDecimal _100 = new BigDecimal("100");
	
	// 功能监区
	private static final List<String> GNJQ = Arrays.asList("一监区", "二监区", "三监区", "四监区");
	// 劳务加工监区
//	private static final List<String> LWJGJQ = Arrays.asList("一监区", "二监区", "三监区", "四监区", "五监区", "七监区", "八监区", "十二监区", "十七监区");
	
	// 单独排名的科室
//	private static final List<String> KS_GROUP1 = Arrays.asList("政治处", "离退休干部科", "综合管理科", "纪委");
	
	@Autowired
	private ResultService resultService;
	@Autowired
	private KhService khService;
	@Autowired
	private SceneService sceneService;
	@Autowired
	private KhRuleService khRuleService;
	@Autowired
	private CpDetailService cpDetailService;
	@Autowired
	private SupService supService;
	@Autowired
	private KhzDeptService khzDeptService;
	@Autowired
	private DictService dictService;

	@RequestMapping("/result")
	public String result(Result result, ModelMap mmap) {
		String pageFlag = result.getPageFlag();
		if (StringUtils.isBlank(pageFlag)) {
			throw new RuntimeException("请求参数错误, pageFlag is blank.");
		}
		
		result.setMonthId(Utils.lastMonth());
		mmap.put("result", result);

		return "rate/resultList";
	}

	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Result result) {
		List<Result> list;
		if (StringUtils.isBlank(result.getMonthId())) {
			list = new ArrayList<Result>();
		} else {
			list = this.resultService.findList(result);
		}
		this.orderResultList(list);

		return getDataTable(list);
	}

	@RequestMapping("/calcAll")
	@ResponseBody
	public AjaxResult calcAll(Result result) {
		if (StringUtils.isBlank(result.getMonthId())) {
			return AjaxResult.error("请选择考核月份");
		}
		
		if (!this.canCalc(result.getMonthId())) {
			return AjaxResult.error("已过期，不允许计算所选月份的数据！");
		}
		
		List<Dept> deptList = Utils.level2DeptList();
		
		/**
		Iterator<Dept> it = deptList.iterator();
		while (it.hasNext()) {
			Dept d = it.next();
			if (this.disappearDept(d)) {
				it.remove();
			}
		}
		**/
		
		List<Result> resultList = this.calc(result.getMonthId(), deptList);
		this.resultService.batchSave(resultList);
		
		this.rank(result.getMonthId());
		
		return AjaxResult.success("计算成功！");
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/export")
	@ResponseBody
	public AjaxResult export(Result r) {
		String monthId = r.getMonthId();
		if (StringUtils.isBlank(monthId)) {
			return AjaxResult.error("请选择月份");
		}
		String monthName = r.getMonthId().replace("-0", "年").replace("-", "年");
		monthName = monthName + "月";
		
		Map<String, String> khzDictMap = Utils.mapDictByValue(Constants.KHZ);
		
		// 查询考核组定义
		List<String> khzList = new ArrayList<String>();
		List<DictData> dictDatas = this.dictService.getType(Constants.KHZ);
		for (DictData dd : dictDatas) {
			khzList.add(dd.getDictValue());
		}
		
		// 将考核部门与考核组映射到一起
		List<KhzDept> khzDeptList = this.khzDeptService.findList(new KhzDept());
		Map<String, List<KhzDept>> khzDeptMap = new HashMap<>();
		for (String khz : khzList) {
			khzDeptMap.put(khz, new ArrayList<KhzDept>());
		}
		for (KhzDept khzDept : khzDeptList) {
			khzDeptMap.get(khzDept.getKhz()).add(khzDept);
		}
		
		HSSFWorkbook wb = null;
		OutputStream out = null;
		String filename = "考核汇总表(" + monthName + ").xls";
		try {
			wb = new HSSFWorkbook();
			Sheet sheet;
			Row row;
			Cell cell;
			CellRangeAddress region;
			int sheetIndex = 0;
			int rowIndex = 0;
			int colIndex = 0;
			
			CellStyle horizontalTextWithSongti11 = Utils.styleOfSongti11Horizontal(wb);
			CellStyle horizontalTextWithSongti11_jichufen = Utils.styleOfSongti11Horizontal(wb);
			this.setBgColor(horizontalTextWithSongti11_jichufen, wb, HSSFColorPredefined.LIGHT_GREEN, 226, 239, 218);
			CellStyle horizontalTextWithSongti11_xianchangfen = Utils.styleOfSongti11Horizontal(wb);
			this.setBgColor(horizontalTextWithSongti11_xianchangfen, wb, HSSFColorPredefined.LIGHT_BLUE, 217, 225, 242);
			CellStyle horizontalTextWithSongti11_cepingfen = Utils.styleOfSongti11Horizontal(wb);
			this.setBgColor(horizontalTextWithSongti11_cepingfen, wb, HSSFColorPredefined.LIGHT_CORNFLOWER_BLUE, 255, 230, 153);
			CellStyle horizontalTextWithSongti11_zhuanxiangfen = Utils.styleOfSongti11Horizontal(wb);
			this.setBgColor(horizontalTextWithSongti11_zhuanxiangfen, wb, HSSFColorPredefined.LIGHT_ORANGE, 234, 224, 222);
			CellStyle horizontalTextWithSongti11_szpyfen = Utils.styleOfSongti11Horizontal(wb);
			this.setBgColor(horizontalTextWithSongti11_szpyfen, wb, HSSFColorPredefined.LIGHT_TURQUOISE, 240, 242, 202);
//			CellStyle verticalTextWithSongti11 = Utils.styleOfSongti11Vertical(wb);
//			CellStyle verticalTextWithSongti11Bold = Utils.styleOfSongti11VerticalBold(wb);
			CellStyle horizontalTextWithSongti20 = Utils.styleOfSongti20Horizontal(wb);
			CellStyle horizontalTextWithSongti14 = Utils.styleOfSongti14Horizontal(wb);
			CellStyle pmStyleDefault = Utils.styleOfPmDefault(wb);
//			CellStyle pmStyle1 = Utils.styleOfPmBlue(wb);
//			CellStyle pmStyle2 = Utils.styleOfPmLemon(wb);
//			CellStyle pmStyle3 = Utils.styleOfPmGreen(wb);
//			CellStyle pmStyle4 = Utils.styleOfPmYellow(wb);
			
			// 排名 begin
			sheet = wb.createSheet();
			wb.setSheetName(sheetIndex++, "排名");
			rowIndex = 0;
			
			// 产生表头1 begin
			colIndex = 0;
			row = sheet.createRow(rowIndex++);
			row.setHeight((short)(45 * 20));
			cell = row.createCell(colIndex++);
			cell.setCellValue("山东省鲁中监狱日常工作综合考核排名(" + monthName + ")");
			cell.setCellStyle(Utils.styleOfSongti20HorizontalBold(wb));
			sheet.setColumnWidth(colIndex - 1, 33 * 256);
			for (int i = 0; i < 2; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 33 * 256);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, 0, colIndex-1);
			sheet.addMergedRegion(region);
			// 产生表头1 end
			
			// 产生表头2 begin
			colIndex = 0;
			row = sheet.createRow(rowIndex++);
			row.setHeight((short)(30 * 20)); 
			cell = row.createCell(colIndex++);
			cell.setCellStyle(horizontalTextWithSongti11);
			cell.setCellValue("部门");
			cell = row.createCell(colIndex++);
			cell.setCellStyle(horizontalTextWithSongti11);
			cell.setCellValue("排名");
			cell = row.createCell(colIndex++);
			cell.setCellStyle(horizontalTextWithSongti11);
			cell.setCellValue("总分");
			// 产生表头2 end
			
			// 写入排名数据 begin
			Result _r1 = new Result();
			_r1.setMonthId(r.getMonthId());
			List<Result> _resultList = this.resultService.findList(_r1);
			Collections.sort(_resultList, new Comparator<Result>() {
				@Override
				public int compare(Result o1, Result o2) {
					if (o1.getPm() != null && o2.getPm() != null && !o1.getPm().equals(o2.getPm())) {
						return o1.getPm().compareTo(o2.getPm());
					}
					return 0;
				}
			});
			// 劳务加工监区、功能监区单独排名,科室单独排名
			List<Result> scjqList = new ArrayList<Result>();
			List<Result> gnjqList = new ArrayList<Result>();
			List<Result> ksList = new ArrayList<Result>();
			List<Result> noKhKsList = new ArrayList<Result>();
			for (Result _r : _resultList) {
				if (Utils.isJq(_r.getDept())) {
					if (this.isScjq(_r.getDept())) {
						scjqList.add(_r);
					} else {
						gnjqList.add(_r);
					}
				} else {
					if (StringUtils.equals("N", _r.getKhbz())) {
						noKhKsList.add(_r);
					} else {
						ksList.add(_r);
					}
				}
			}
			short columnHeight = 35 * 20;
			for (Result _r : gnjqList) {
				colIndex = 0;
				row = sheet.createRow(rowIndex++);
				row.setHeight(columnHeight); 
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(_r.getDept().getDeptName());
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(_r.getPm());
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(this.formatNumber(_r.getZdf(), false));
			}
			colIndex = 0;
			row = sheet.createRow(rowIndex++);
			row.setHeight(columnHeight);
			cell = row.createCell(colIndex++);
			cell.setCellValue("");
			cell.setCellStyle(horizontalTextWithSongti11);
			for (int i = 0; i < 2; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, 0, colIndex-1);
			sheet.addMergedRegion(region);
			for (Result _r : scjqList) {
				colIndex = 0;
				row = sheet.createRow(rowIndex++);
				row.setHeight(columnHeight); 
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(_r.getDept().getDeptName());
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(_r.getPm());
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(this.formatNumber(_r.getZdf(), false));
			}
			colIndex = 0;
			row = sheet.createRow(rowIndex++);
			row.setHeight(columnHeight);
			cell = row.createCell(colIndex++);
			cell.setCellValue("");
			cell.setCellStyle(horizontalTextWithSongti11);
			for (int i = 0; i < 2; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, 0, colIndex-1);
			sheet.addMergedRegion(region);
			for (Result _r : ksList) {
				colIndex = 0;
				row = sheet.createRow(rowIndex++);
				row.setHeight(columnHeight); 
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(_r.getDept().getDeptName());
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(_r.getPm());
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(this.formatNumber(_r.getZdf(), false));
			}
			colIndex = 0;
			row = sheet.createRow(rowIndex++);
			row.setHeight(columnHeight);
			cell = row.createCell(colIndex++);
			cell.setCellValue("");
			cell.setCellStyle(horizontalTextWithSongti11);
			for (int i = 0; i < 2; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, 0, colIndex-1);
			sheet.addMergedRegion(region);
			for (Result _r : noKhKsList) {
				colIndex = 0;
				row = sheet.createRow(rowIndex++);
				row.setHeight(columnHeight); 
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(_r.getDept().getDeptName());
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue("参与考核，不参与排名");
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
				cell.setCellValue(this.formatNumber(_r.getZdf(), false));
			}
			// 写入排名数据 end
			// 排名 end
			
			// 汇总表 begin
			sheet = wb.createSheet();
			wb.setSheetName(sheetIndex++, "汇总表");
			rowIndex = 0;
			
			// 产生表头0 begin
			colIndex = 0;
			int jcywkh_cols = 0; // 基础业务考核列总数
			for (List<KhzDept> list :khzDeptMap.values()) {
				jcywkh_cols = jcywkh_cols + list.size() + 1; // 每个考核组有一个权重得分
			}
			jcywkh_cols = jcywkh_cols + 2; // 增加考核办得分及权重，两列
			int xcglkh_cols = 2; // 现场管理2列
			int cpkh_cols = 4; // 测评考核
			int totalSize = jcywkh_cols
					+ 1 // 单位1列
					+ xcglkh_cols
					+ cpkh_cols
					+ 1 // 专项考核
					+ 1 // 述职评议
					+ 1 // 负面清单
					+ 1 // 总分
					; // 总列数
			row = sheet.createRow(rowIndex++);
			row.setHeight((short)(40 * 20));
			cell = row.createCell(colIndex++);
			cell.setCellValue("鲁中监狱日常工作考核汇总表(" + monthName + ")");
			cell.setCellStyle(Utils.styleOfSongti20HorizontalBold(wb));
			for (int i = 0; i < (totalSize - 1); i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, colIndex - totalSize, colIndex-1);
			sheet.addMergedRegion(region);
			// 产生表头0 end
			
			// 产生表头1 begin
			colIndex = 0;
			row = sheet.createRow(rowIndex++);
			row.setHeight((short)(38 * 20)); 
			cell = row.createCell(colIndex++);
			cell.setCellStyle(horizontalTextWithSongti11);
			cell.setCellValue("项目");
			// --C1
			cell = row.createCell(colIndex++);
			cell.setCellValue("基础业务考核");
			cell.setCellStyle(horizontalTextWithSongti11_jichufen);
			for (int i = 0; i < (jcywkh_cols - 1); i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, colIndex - jcywkh_cols, colIndex-1);
			sheet.addMergedRegion(region);
			// --C2
			cell = row.createCell(colIndex++);
			cell.setCellValue("现场管理考核");
			cell.setCellStyle(horizontalTextWithSongti11_xianchangfen);
			for (int i = 0; i < (xcglkh_cols - 1); i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, colIndex - xcglkh_cols, colIndex-1);
			sheet.addMergedRegion(region);
			// --C3
			cell = row.createCell(colIndex++);
			cell.setCellValue("测评考核");
			cell.setCellStyle(horizontalTextWithSongti11_cepingfen);
			for (int i = 0; i < (cpkh_cols - 1); i++) {
				cell = row.createCell(colIndex++);
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			region = new CellRangeAddress(rowIndex-1, rowIndex-1, colIndex - cpkh_cols, colIndex-1);
			sheet.addMergedRegion(region);
			// --C4~
			cell = row.createCell(colIndex++);
			cell.setCellValue("专项考核");
			cell.setCellStyle(horizontalTextWithSongti11_zhuanxiangfen);
			sheet.setColumnWidth(colIndex - 1, 6 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("述职评议");
			cell.setCellStyle(horizontalTextWithSongti11_szpyfen);
			sheet.setColumnWidth(colIndex - 1, 6 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("负面清单");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 4 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("总分");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 6 * 256);
			// 产生表头1 end
			
			// 产生表头2 begin
			colIndex = 0;
			row = sheet.createRow(rowIndex++);
			row.setHeight((short)(38 * 20));
			cell = row.createCell(colIndex++);
			cell.setCellValue("单位");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 8 * 256);
			for (String khz : khzList) {
				cell = row.createCell(colIndex++);
				cell.setCellValue(khzDictMap.get(khz));
				cell.setCellStyle(horizontalTextWithSongti11);
				int deptsSize = khzDeptMap.get(khz).size(); // 考核组下面的部门个数
				for (int i = 0; i < deptsSize; i++) {
					// 去除第一个已填充，额外增加一列
					cell = row.createCell(colIndex++);
					cell.setCellValue("");
				}
				region = new CellRangeAddress(rowIndex-1, rowIndex-1, colIndex-1 - deptsSize, colIndex-1);
				sheet.addMergedRegion(region);
			}
			int mergeBeginCol = colIndex; // 从综合考核办开始合并
			cell = row.createCell(colIndex++);
			cell.setCellValue("综合考核办");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 6 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("按权重测算得分");
			cell.setCellStyle(horizontalTextWithSongti11_jichufen);
			sheet.setColumnWidth(colIndex - 1, 7 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("现场管理考核得分");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 6 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("按权重测算得分");
			cell.setCellStyle(horizontalTextWithSongti11_xianchangfen);
			sheet.setColumnWidth(colIndex - 1, 7 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("监狱领导");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 6 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("科室");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 6 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("监区");
			cell.setCellStyle(horizontalTextWithSongti11);
			sheet.setColumnWidth(colIndex - 1, 6 * 256);
			cell = row.createCell(colIndex++);
			cell.setCellValue("按权重测算得分");
			cell.setCellStyle(horizontalTextWithSongti11_cepingfen);
			sheet.setColumnWidth(colIndex - 1, 7 * 256);
			// 专项考核、述职评议、负面清单、总分
			for (int i = 0; i < 4; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellValue("");
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			// 产生表头2end
			
			// 产生表头3begin
			colIndex = 0;
			row = sheet.createRow(rowIndex++);
			row.setHeight((short)(75 * 20));
			cell = row.createCell(colIndex++);
			cell.setCellValue("");
			cell.setCellStyle(horizontalTextWithSongti11);
			// 基础业务考核
			for (String khz : khzList) {
				List<KhzDept> _t = khzDeptMap.get(khz);
				for (KhzDept _u : _t) {
					cell = row.createCell(colIndex++);
					cell.setCellValue(_u.getDept().getDeptName());
					cell.setCellStyle(horizontalTextWithSongti11);
					sheet.setColumnWidth(colIndex - 1, 6 * 256);
				}
				cell = row.createCell(colIndex++);
				cell.setCellValue("按权重测算得分");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 7 * 256);
			}
			// 综合考核办
			cell = row.createCell(colIndex++);
			cell.setCellValue("");
			cell.setCellStyle(horizontalTextWithSongti11);
			// 权重得分
			cell = row.createCell(colIndex++);
			cell.setCellValue("");
			cell.setCellStyle(horizontalTextWithSongti11);
			// 现场管理考核2列
			for (int i = 0; i < xcglkh_cols; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellValue("");
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			// 测评考核
			for (int i = 0; i < cpkh_cols; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellValue("");
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			// 专项考核、述职评议、负面清单、总分
			for (int i = 0; i < 4; i++) {
				cell = row.createCell(colIndex++);
				cell.setCellValue("");
				cell.setCellStyle(horizontalTextWithSongti11);
			}
			// 产生表头3end
			
			// 合并表头单元格 begin
			region = new CellRangeAddress(2, 3, 0, 0); // 合并单位
			sheet.addMergedRegion(region);
			region = new CellRangeAddress(2, 3, mergeBeginCol, mergeBeginCol); // 合并综合考核办
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(2, 3, mergeBeginCol, mergeBeginCol); // 合并按权重测算得分
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(2, 3, mergeBeginCol, mergeBeginCol); // 合并现场管理考核得分
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(2, 3, mergeBeginCol, mergeBeginCol); // 合并按权重测算得分
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(2, 3, mergeBeginCol, mergeBeginCol); // 合并监狱领导
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(2, 3, mergeBeginCol, mergeBeginCol); // 合并科室
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(2, 3, mergeBeginCol, mergeBeginCol); // 合并监区
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(2, 3, mergeBeginCol, mergeBeginCol); // 合并按权重测算得分
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(1, 3, mergeBeginCol, mergeBeginCol); // 合并专项考核
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(1, 3, mergeBeginCol, mergeBeginCol); // 合并述职评议
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(1, 3, mergeBeginCol, mergeBeginCol); // 合并负面清单
			sheet.addMergedRegion(region);
			mergeBeginCol++;
			region = new CellRangeAddress(1, 3, mergeBeginCol, mergeBeginCol); // 合并总分
			sheet.addMergedRegion(region);
			// 合并表头单元格 end
			
			// 以下填充数据
			Result _result = new Result();
			_result.setMonthId(r.getMonthId());
			List<Result> resultList = this.resultService.findList(_result);
			this.orderResultList(resultList); // 将不参与考核的单位放到最后
//			int xh = 1; // 序号
			for (Result result : resultList) {// 填充数据
				CellStyle cellStyle = pmStyleDefault;
				/**
				if (StringUtils.equals("1", result.getPmColor())) {
					cellStyle = pmStyle1;
				} else if (StringUtils.equals("2", result.getPmColor())) {
					cellStyle = pmStyle2;
				} else if (StringUtils.equals("3", result.getPmColor())) {
					cellStyle = pmStyle3;
				} else if (StringUtils.equals("4", result.getPmColor())) {
					cellStyle = pmStyle4;
				} else {
					cellStyle = pmStyleDefault;
				}
				**/
				
				colIndex = 0;
				row = sheet.createRow(rowIndex++);
				row.setHeight((short)(55 * 20));
				cell = row.createCell(colIndex++);
				cell.setCellValue(result.getDept().getDeptName());
				cell.setCellStyle(cellStyle);
				Map<String, Object> jsonOfDuKf = (Map<String, Object>)JSON.parseObject(result.getJsonOfDuKf());
				// 督办得分 begin
				for (String khz : khzList) {
					List<KhzDept> _t = khzDeptMap.get(khz);
					Map<String, Object> khzMap = (Map<String, Object>)jsonOfDuKf.get(khz);// 督办扣分详情  khz-(deptId-(details map))
					if (khzMap == null) {
						khzMap = new HashMap<String, Object>();
					}
					for (KhzDept _u : _t) {
						Map<String, String> deptMap = (Map<String, String>)khzMap.get(_u.getDept().getDeptId() + "");
						if (deptMap == null) {
							deptMap = new HashMap<String, String>();
						}
						cell = row.createCell(colIndex++);
						cell.setCellValue(this.formatNumber(deptMap.get("kf"), false)); // 每一个部门的扣分情况
						// cell.setCellType(CellType.NUMERIC);
						cell.setCellStyle(cellStyle);
					}
					
					// 每个考核组的得分（带权重）
					cell = row.createCell(colIndex++);
					BigDecimal dfQz = null;
					if ("001".equals(khz)) {
						dfQz = result.getDf001qz();
					} else if ("002".equals(khz)) {
						dfQz = result.getDf002qz();
					} else if ("003".equals(khz)) {
						dfQz = result.getDf003qz();
					} else if ("004".equals(khz)) {
						dfQz = result.getDf004qz();
					}
					cell.setCellValue(this.formatNumber(dfQz, false));
					cell.setCellStyle(cellStyle);
				}
				// 综合考核办
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getKhb(), false));
				cell.setCellStyle(cellStyle);
				// sheet.setColumnWidth(colIndex - 1, 15 * 256);
				// 基础考核-权重得分
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getJcfqz(), false));
				cell.setCellStyle(cellStyle);
				// sheet.setColumnWidth(colIndex - 1, 15 * 256);
				// 督办得分 end
				// 现场管理考核 begin
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getTotalxckh(), false));
				cell.setCellStyle(cellStyle);
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getXckhqz(), false));
				cell.setCellStyle(cellStyle);
				// 现场管理考核 end
				// 测评考核 begin
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getLdcpfpjz(), false));
				cell.setCellStyle(cellStyle);
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getKscpfpjz(), false));
				cell.setCellStyle(cellStyle);
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getJqcpfpjz(), false));
				cell.setCellStyle(cellStyle);
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getCpfqz(), false));
				cell.setCellStyle(cellStyle);
				// 测评考核 end
				// 专项考核
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getZxkh(), false));
				cell.setCellStyle(cellStyle);
				// 述职评议考核
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getSzpy(), false));
				cell.setCellStyle(cellStyle);
				// 负面清单
				cell = row.createCell(colIndex++);
				String cellValue = "";
				if (result.getSupfmqd() != null && result.getSupfmqd() > 0) {
					cellValue = "是";
				}
				cell.setCellValue(cellValue);
				cell.setCellStyle(cellStyle);
				// 总分
				cell = row.createCell(colIndex++);
				cell.setCellValue(this.formatNumber(result.getZdf(), false));
				cell.setCellStyle(cellStyle);
			}
			// 汇总表 end
			
			// 每个部门一个扣分表 begin
			List<Dept> deptList = Utils.level2DeptList();
			/**
			Iterator<Dept> it = deptList.iterator();
			while (it.hasNext()) {
				Dept d = it.next();
				if (this.disappearDept(d)) {
					it.remove();
				}
			}
			**/
			for (Dept dept : deptList) {
				sheet = wb.createSheet();
				wb.setSheetName(sheetIndex++, dept.getDeptName());
				rowIndex = 0;
				
				// 一级表头 begin
				row = sheet.createRow(rowIndex++);
				row.setHeight((short)(50 * 20));
				colIndex = 0;
				cell = row.createCell(colIndex++);
				cell.setCellValue("鲁中监狱日常工作考核汇总表");
				cell.setCellStyle(horizontalTextWithSongti20);
				for (int i = 0; i < 7; i++) {
					cell = row.createCell(colIndex++);
					cell.setCellStyle(horizontalTextWithSongti20);
				}
				region = new CellRangeAddress(rowIndex-1, rowIndex-1, 0, colIndex - 1);
				sheet.addMergedRegion(region);
				// 一级表头 end
				
				// 二级表头 begin
				row = sheet.createRow(rowIndex++);
				row.setHeight((short)(25 * 20));
				colIndex = 0;
				cell = row.createCell(colIndex++);
				cell.setCellValue("单位：" + dept.getDeptName());
				cell.setCellStyle(horizontalTextWithSongti14);
				region = new CellRangeAddress(rowIndex-1, rowIndex-1, colIndex - 1, colIndex + 1);
				sheet.addMergedRegion(region);
				// 二级表头 end
				
				// 三级表头 begin
				row = sheet.createRow(rowIndex++);
				row.setHeight((short)(40 * 20));
				colIndex = 0;
				cell = row.createCell(colIndex++);
				cell.setCellValue("业务考核组");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 10 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("考核单位");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 10 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("考核序号");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 9 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("考核项目");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 27 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("考核内容及标准");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 40 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("考核情况");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 24 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("得分");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 9 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("考核责任人");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 11 * 256);
				// 三级表头 end
				
				// 扣分项 begin
				List<Kh> khList = new ArrayList<Kh>();
				Kh _kh = new Kh();
				_kh.setDept(dept);
				_kh.setMonthId(monthId);
				_kh.setStatus(Constants.KH_STATUS_APPROVED);
				_kh.setType(Constants.KH_TYPE_ZHU); // 主办
				List<Kh> temp = this.khService.findList(_kh);
				khList.addAll(temp);
				
				_kh.setType(Constants.KH_TYPE_KHB_ZB); // 考核办-主办
				khList.addAll(this.khService.findList(_kh));
				
				_kh.setType(Constants.KH_TYPE_DU); // 督办考核
				temp = this.khService.findList(_kh);
				// 按照考核组进行排序
				Collections.sort(temp, new Comparator<Kh>() {
					@Override
					public int compare(Kh o1, Kh o2) {
						String khz1 = o1.getKhz();
						String khz2 = o2.getKhz();
						if (StringUtils.isNotBlank(khz1) && StringUtils.isNotBlank(khz2)) {
							return khz1.compareTo(khz2);
						}
						return 0;
					}
				});
				khList.addAll(temp);
				
				// 主办、督办扣分 begin
				for (Kh kh : khList) {
					int rowsSpan = 0;
					boolean hasKf = false;
					KhRule _khRule = new KhRule();
					_khRule.setKh(kh);
					List<KhRule> khRuleList = this.khRuleService.findList(_khRule);
					for (KhRule khRule : khRuleList) {
						if (khRule.getKf() != null && khRule.getKf().compareTo(ZERO) != 0) {
							hasKf = true;
							row = sheet.createRow(rowIndex++);
							rowsSpan++;
							colIndex = 0;
							cell = row.createCell(colIndex++);
							if (StringUtils.equals(Constants.KH_TYPE_ZHU, kh.getType())) {
								cell.setCellValue("主办业务");
							} else if (StringUtils.equals(Constants.KH_TYPE_DU, kh.getType())) {
								cell.setCellValue(khzDictMap.get(kh.getKhz()));
							} else if (StringUtils.equals(Constants.KH_TYPE_KHB_ZB, kh.getType())) {
								cell.setCellValue("主办业务");
							}
							cell.setCellStyle(horizontalTextWithSongti11);
							cell = row.createCell(colIndex++);
							if (StringUtils.equals(Constants.KH_TYPE_ZHU, kh.getType())) {
								cell.setCellValue(dept.getDeptName());
							} else if (StringUtils.equals(Constants.KH_TYPE_DU, kh.getType())) {
								cell.setCellValue(kh.getCreateDept().getDeptName());
							} else if (StringUtils.equals(Constants.KH_TYPE_KHB_ZB, kh.getType())) {
								cell.setCellValue("综合考核办公室");
							}
							cell.setCellStyle(horizontalTextWithSongti11);
							cell = row.createCell(colIndex++);
							cell.setCellValue(khRule.getXh());
							cell.setCellStyle(horizontalTextWithSongti11);
							cell = row.createCell(colIndex++);
							cell.setCellValue(khRule.getXm());
							cell.setCellStyle(horizontalTextWithSongti11);
							cell = row.createCell(colIndex++);
							cell.setCellValue(khRule.getNr());
							cell.setCellStyle(horizontalTextWithSongti11);
							cell = row.createCell(colIndex++);
							cell.setCellValue(khRule.getRemark());
							cell.setCellStyle(horizontalTextWithSongti11);
							cell = row.createCell(colIndex++);
							cell.setCellValue(this.formatNumber(khRule.getKf(), false));
							cell.setCellStyle(horizontalTextWithSongti11);
							cell = row.createCell(colIndex++);
							cell.setCellValue(khRule.getZrr());
							cell.setCellStyle(horizontalTextWithSongti11);
						}
					}
					
					if (!hasKf) {
						row = sheet.createRow(rowIndex++);
						row.setHeight((short)(40 * 20));
						rowsSpan++;
						
						colIndex = 0;
						cell = row.createCell(colIndex++);
						if (StringUtils.equals(Constants.KH_TYPE_ZHU, kh.getType())) {
							cell.setCellValue("主办业务");
						} else if (StringUtils.equals(Constants.KH_TYPE_DU, kh.getType())) {
							cell.setCellValue(khzDictMap.get(kh.getKhz()));
						} else {
						}
						cell.setCellStyle(horizontalTextWithSongti11);
						cell = row.createCell(colIndex++);
						if (StringUtils.equals(Constants.KH_TYPE_ZHU, kh.getType())) {
							cell.setCellValue("无");
						} else if (StringUtils.equals(Constants.KH_TYPE_DU, kh.getType())) {
							cell.setCellValue(kh.getCreateDept().getDeptName());
						} else {
						}
						cell.setCellStyle(horizontalTextWithSongti11);
						for (int i = 0; i < 6; i++) {
							cell = row.createCell(colIndex++);
							cell.setCellValue("");
							cell.setCellStyle(horizontalTextWithSongti11);
						}
					}
					
					if (rowsSpan > 1) {
						region = new CellRangeAddress(rowIndex - rowsSpan, rowIndex-1, 0, 0);
						sheet.addMergedRegion(region);
						region = new CellRangeAddress(rowIndex - rowsSpan, rowIndex-1, 1, 1);
						sheet.addMergedRegion(region);
					}
				}
				// 主办、督办扣分 end
				// 扣分项 end
			}
			// 每个部门一个扣分表 end
			
			// 专项加分、扣分、述职评议、综合考核办begin
			List<String> supTypes = Arrays.asList(Constants.SUP_TYPE_JF, Constants.SUP_TYPE_KF,
					Constants.SUP_TYPE_SZPY, Constants.SUP_TYPE_KHB);
			for (String supType : supTypes) {
				sheet = wb.createSheet();
				String sheetName = supType;
				if (StringUtils.equals(Constants.SUP_TYPE_JF, supType)) {
					sheetName = "专项加分";
				} else if (StringUtils.equals(Constants.SUP_TYPE_KF, supType)) {
					sheetName = "专项扣分";
				} else if (StringUtils.equals(Constants.SUP_TYPE_SZPY, supType)) {
					sheetName = "述职评议";
				} else if (StringUtils.equals(Constants.SUP_TYPE_KHB, supType)) {
					sheetName = "综合考核办";
				}
				wb.setSheetName(sheetIndex++, sheetName);
				rowIndex = 0;
				
				// 一级表头 begin
				row = sheet.createRow(rowIndex++);
				row.setHeight((short)(50 * 20));
				colIndex = 0;
				cell = row.createCell(colIndex++);
				String month = monthId.substring(monthId.length() - 2);
				if (month.startsWith("0")) {
					month = month.substring(1);
				}
				cell.setCellValue("鲁中监狱" + month + "月份日常工作考核专项" + sheetName + "表");
				cell.setCellStyle(horizontalTextWithSongti20);
				for (int i = 0; i < 3; i++) {
					cell = row.createCell(colIndex++);
					cell.setCellStyle(horizontalTextWithSongti20);
				}
				region = new CellRangeAddress(rowIndex-1, rowIndex-1, 0, colIndex - 1);
				sheet.addMergedRegion(region);
				// 一级表头 end
				
				// 二级表头 begin
				row = sheet.createRow(rowIndex++);
				row.setHeight((short)(40 * 20));
				colIndex = 0;
				cell = row.createCell(colIndex++);
				cell.setCellValue("考核单位");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 15 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("被考核单位");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 15 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue(sheetName);
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 9 * 256);
				cell = row.createCell(colIndex++);
				cell.setCellValue("详情");
				cell.setCellStyle(horizontalTextWithSongti11);
				sheet.setColumnWidth(colIndex - 1, 50 * 256);
				// 二级表头 end
				
				// 加分、扣分项 begin
				Sup sup = new Sup();
				sup.setMonthId(monthId);
				sup.setType(supType);
				sup.setStatus(Constants.KH_STATUS_APPROVED);
				List<Sup> supList = this.supService.findList(sup);
				for (Sup s : supList) {
					row = sheet.createRow(rowIndex++);
					// row.setHeight((short)(25 * 20));
					colIndex = 0;
					cell = row.createCell(colIndex++);
					cell.setCellValue(s.getCreateDept().getDeptName());
					cell.setCellStyle(horizontalTextWithSongti11);
					cell = row.createCell(colIndex++);
					cell.setCellValue(s.getDept().getDeptName());
					cell.setCellStyle(horizontalTextWithSongti11);
					cell = row.createCell(colIndex++);
					cell.setCellValue(s.getScore().toString());
					cell.setCellStyle(horizontalTextWithSongti11);
					cell = row.createCell(colIndex++);
					cell.setCellValue(s.getContent1());
					cell.setCellStyle(horizontalTextWithSongti11);
				}
			}
			// 专项加分、扣分、述职评议、综合考核办begin
			
			String filepath = Utils.getExportAbsoluteFile(filename);
			File file = new File(filepath);
			if (file.exists() && file.isFile()) {
				file.delete();
			}
			out = new FileOutputStream(filepath);
			wb.write(out);
			return AjaxResult.success(filename);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("导出Excel失败，请联系网站管理员！");
		} finally {
			IOUtils.closeQuietly(wb);
			IOUtils.closeQuietly(out);
		}
	}
	
	private List<Result> calc(String monthId, List<Dept> deptList) {
		List<Result> resultList = new ArrayList<Result>();
		
		for (Dept dept : deptList) {
			Result result = new Result();
			result.setMonthId(monthId);
			result.setDept(dept);
			
			if (Utils.isJq(dept)) {
				result.setDeptType(Constants.DEPT_TYPE_JQ);
			} else {
				result.setDeptType(Constants.DEPT_TYPE_KS);
			}
			
			// process kh 计算基础分
			this.processKh(result);
			
			// process scene 计算现场考核分
			this.processXckh(result);
			
			// process sup 计算加分、减分、负面清单
			this.processSup(result);
			
			// process cp 计算测评分
			this.processCp(result);
			
			// process total 计算总分
			this.processTotal(result);
			
			resultList.add(result);
		}
		
		return resultList;
	}
	
	/**
	 * 处理现场考核
	 * @param result
	 */
	private void processXckh(Result result) {
		Scene _scene = new Scene();
		_scene.setMonthId(result.getMonthId());
		_scene.setStatus(Constants.KH_STATUS_APPROVED);
		_scene.setDept(result.getDept());
		List<Scene> sceneList = this.sceneService.findList(_scene);
		
		BigDecimal totalxckh = ZERO;
		BigDecimal xckhqz = ZERO;
		
		for (Scene scene : sceneList) {
			totalxckh = totalxckh.add(scene.getScore());
		}
		
		/**
		 * 监区：现场考核占总分的0.3
		 * 科室：无现场考核
		 */
		if (Utils.isJq(result.getDept())) {
			xckhqz = round2(_100.add(totalxckh).multiply(new BigDecimal("0.3")));
		}
		
		result.setTotalxckh(totalxckh);
		result.setXckhqz(xckhqz);
	}
	
	private void processKh(Result result) {
		Kh _kh = new Kh();
		_kh.setMonthId(result.getMonthId());
		_kh.setStatus(Constants.KH_STATUS_APPROVED);
		_kh.setDept(result.getDept());
		List<Kh> khList = this.khService.findList(_kh);
		
		BigDecimal kf001 = ZERO;
		BigDecimal kf002 = ZERO;
		BigDecimal kf003 = ZERO;
		BigDecimal kf004 = ZERO;
		BigDecimal kfzhu = ZERO;
		BigDecimal kfKhbZhu = ZERO; // 考核办主办扣分
//		String khzOfZB = null; // 主办考核组
		/**
		 * 督办扣分详情  khz-(deptId-(details map))
		 * khz
		 * --kf
		 * --deptId
		 * ----deptId
		 * ----deptName
		 * ----kf
		 */
		Map<String, Map<String, Object>> jsonOfDuKf = new HashMap<>();
		for (Kh kh : khList) {
			if (Constants.KH_TYPE_ZHU.equals(kh.getType())) {
//				kfzhu = kfzhu.add(kh.getKf());
//				khzOfZB = kh.getKhz();
			} else if (Constants.KH_TYPE_KHB_ZB.equals(kh.getType())) {
//				kfzhu = kfzhu.add(kh.getKf());
//				kfKhbZhu = kfKhbZhu.add(kh.getKf());
			} else if (Constants.KH_TYPE_DU.equals(kh.getType())) {
				String khz = kh.getKhz();
				Map<String, Object> khzValue = null;
				if (jsonOfDuKf.containsKey(khz)) {
					khzValue = jsonOfDuKf.get(khz);
				} else {
					khzValue = new HashMap<String, Object>();
					jsonOfDuKf.put(khz, khzValue);
				}
				
				if ("001".equals(khz)) {
					kf001 = kf001.add(kh.getKf());
					khzValue.put("kf", kf001.toString());
				} else if ("002".equals(khz)) {
					kf002 = kf002.add(kh.getKf());
					khzValue.put("kf", kf002.toString());
				} else if ("003".equals(khz)) {
					kf003 = kf003.add(kh.getKf());
					khzValue.put("kf", kf003.toString());
				} else if ("004".equals(khz)) {
					kf004 = kf004.add(kh.getKf());
					khzValue.put("kf", kf004.toString());
				}
				
				Map<String, String> value = new HashMap<String, String>();
				value.put("deptId", kh.getCreateDept().getDeptId() + "");
				value.put("deptName", kh.getCreateDept().getDeptName() + "");
				value.put("kf", kh.getKf() == null ? "" : kh.getKf().toString());
				khzValue.put(kh.getCreateDept().getDeptId() + "", value);
			}
		}
		result.setKf001(kf001);
		result.setKf002(kf002);
		result.setKf003(kf003);
		result.setKf004(kf004);
		result.setKfzhu(kfzhu);
		result.setKfKhbZhu(kfKhbZhu);
		result.setJcfkf(kf001.add(kf002).add(kf003).add(kf004)); // 基础分扣分
		result.setJsonOfDuKf(JSON.toJSONString(jsonOfDuKf)); // 督办考核扣分
		
		BigDecimal df001qz = ZERO;
		BigDecimal df002qz = ZERO;
		BigDecimal df003qz = ZERO;
		BigDecimal df004qz = ZERO;
		BigDecimal dfzhuqz = ZERO;
		if (Utils.isJq(result.getDept())) {
			/**
			 * 监区基础分：
			 * 监管改造001基础分占0.5，
			 * 劳动改造002基础分占0.1，
			 * 队伍管理003基础分占0.3，
			 * 综合保障004基础分占0.1。
			 */
			df001qz = round2((_100.add(kf001)).multiply(new BigDecimal("0.5")));
			df002qz = round2((_100.add(kf002)).multiply(new BigDecimal("0.1")));
			df003qz = round2((_100.add(kf003)).multiply(new BigDecimal("0.3")));
			df004qz = round2((_100.add(kf004)).multiply(new BigDecimal("0.1")));
		} else {
			/**
			 * 科室基础分：
			 * 队伍管理基础分占0.6，
			 * 综合保障基础分占0.4。
			 */
			df001qz = ZERO;
			df002qz = ZERO;
			df003qz = round2((_100.add(kf003)).multiply(new BigDecimal("0.6")));
			df004qz = round2((_100.add(kf004)).multiply(new BigDecimal("0.4")));
		}
		
		// 处理综合考核办的加减分 begin
		Sup sup = new Sup();
		sup.setMonthId(result.getMonthId());
		sup.setDept(result.getDept());
		sup.setStatus(Constants.KH_STATUS_APPROVED);
		sup.setType(Constants.SUP_TYPE_KHB);
		List<Sup> supList = this.supService.findList(sup);
		
		BigDecimal khb = ZERO; // 考核办
		if (supList.size() > 0) {
			for (Sup s : supList) {
				if (s.getScore() != null) {
					khb = khb.add(s.getScore());
				}
			}
		}
		result.setKhb(khb);
		// 处理综合考核办的加减分 end
		
		/**
		 * 基础分（带权重）计算公式：
		 * 监区：四个考核组相加*0.5+考核办
		 * 科室：两个考核组相加*0.6+考核办
		 */
		BigDecimal jcfqz;
		if (Utils.isJq(result.getDept())) {
			jcfqz = round2((df001qz.add(df002qz).add(df003qz).add(df004qz)).multiply(new BigDecimal("0.5")).add(result.getKhb()));
		} else {
			jcfqz = round2((df001qz.add(df002qz).add(df003qz).add(df004qz)).multiply(new BigDecimal("0.6")).add(result.getKhb()));
		}
		result.setDf001qz(df001qz);
		result.setDf002qz(df002qz);
		result.setDf003qz(df003qz);
		result.setDf004qz(df004qz);
		result.setDfzhuqz(dfzhuqz);
		result.setJcfqz(jcfqz);
	}
	
	/**
	 * 处理专项加分、扣分、负面清单、述职评议
	 * @param result
	 */
	private void processSup(Result result) {
		Sup sup = new Sup();
		sup.setMonthId(result.getMonthId());
		sup.setDept(result.getDept());
		sup.setStatus(Constants.KH_STATUS_APPROVED);
		List<Sup> supList = this.supService.findList(sup);
		
		BigDecimal supkf = ZERO;
		BigDecimal supjf = ZERO;
		BigDecimal szpy = ZERO; // 述职评议
		int supfmqd = 0;
		if (supList.size() > 0) {
			for (Sup s : supList) {
				if (Constants.SUP_TYPE_JF.equals(s.getType()) && s.getScore() != null) {
					supjf = supjf.add(s.getScore());
				} else if (Constants.SUP_TYPE_KF.equals(s.getType()) && s.getScore() != null) {
					supkf = supkf.add(s.getScore());
				} else if (Constants.SUP_TYPE_FMQD.equals(s.getType())) {
					supfmqd++;
				} else if (Constants.SUP_TYPE_KHB.equals(s.getType())) {
					// 专项考核放到基础分处理逻辑里
				} else if (Constants.SUP_TYPE_SZPY.equals(s.getType())) {
					szpy = szpy.add(s.getScore());
				}
			}
		}
		
		if (supjf.compareTo(ZERO) != 0) {
			result.setSupjf(supjf);
		}
		if (supkf.compareTo(ZERO) != 0) {
			result.setSupkf(supkf);
		}
		if (supfmqd != 0) {
			result.setSupfmqd(supfmqd);
		}
		if (szpy.compareTo(ZERO) != 0) {
			result.setSzpy(szpy);
		}
		BigDecimal zxkh = supjf.add(supkf);
		if (zxkh.compareTo(ZERO) != 0) {
			result.setZxkh(zxkh);
		}
	}
	
	private void processCp(Result result) {
		Cp cp = new Cp();
		cp.setMonthId(result.getMonthId());
		cp.setStatus(Constants.CP_STATUS_APPROVED);
		CpDetail cpDetail = new CpDetail();
		cpDetail.setCp(cp);
		cpDetail.setDept(result.getDept());
		List<CpDetail> cpDetailList = this.cpDetailService.findList(cpDetail);
		
		BigDecimal totalLdcpf = ZERO;
		BigDecimal totalCjcpf = ZERO;
		BigDecimal totalKscpf = ZERO;
		BigDecimal totalJqcpf = ZERO;
		int ldcprs = 0;
		int cjcprs = 0;
		int kscprs = 0;
		int jqcprs = 0;
		for (CpDetail detail : cpDetailList) {
			if (Constants.CP_TYPE_LD.equals(detail.getCp().getType())) {
				totalLdcpf = totalLdcpf.add(detail.getScore());
				ldcprs++;
			}else if (Constants.CP_TYPE_CJ.equals(detail.getCp().getType())) {
				totalCjcpf = totalCjcpf.add(detail.getScore());
				cjcprs++;
			} else if (Constants.CP_TYPE_KS.equals(detail.getCp().getType())) {
				totalKscpf = totalKscpf.add(detail.getScore());
				kscprs++;
			} else if (Constants.CP_TYPE_JQ.equals(detail.getCp().getType())) {
				totalJqcpf = totalJqcpf.add(detail.getScore());
				jqcprs++;
			}
		}
		result.setTotalldcpf(totalLdcpf);
		result.setTotalcjcpf(totalCjcpf);
		result.setTotalkscpf(totalKscpf);
		result.setTotaljqcpf(totalJqcpf);
		result.setLdcprs(ldcprs);
		result.setCjcprs(cjcprs);
		result.setKscprs(kscprs);
		result.setJqcprs(jqcprs);
		
		// 计算平均值
		BigDecimal ldcpfpjz = ZERO;
		BigDecimal cjcpfpjz = ZERO;
		BigDecimal kscpfpjz = ZERO;
		BigDecimal jqcpfpjz = ZERO;
		if (ldcprs > 0) {
			ldcpfpjz = totalLdcpf.divide(new BigDecimal(ldcprs), 1, BigDecimal.ROUND_HALF_UP);
		}
		if (cjcprs > 0) {
			cjcpfpjz = totalCjcpf.divide(new BigDecimal(cjcprs), 1, BigDecimal.ROUND_HALF_UP);
		}
		if (kscprs > 0) {
			kscpfpjz = totalKscpf.divide(new BigDecimal(kscprs), 1, BigDecimal.ROUND_HALF_UP);
		}
		if (jqcprs > 0) {
			jqcpfpjz = totalJqcpf.divide(new BigDecimal(jqcprs), 1, BigDecimal.ROUND_HALF_UP);
		}
		result.setLdcpfpjz(ldcpfpjz);
		result.setCjcpfpjz(cjcpfpjz);
		result.setKscpfpjz(kscpfpjz);
		result.setJqcpfpjz(jqcpfpjz);
		
		/**
		 * 测评分计算公式：
		 * 监区：领导0.4，科室0.3，监区0.3，合计占总结果的0.2
		 * 科室：领导0.4，科室0.2，监区0.4，合计占总结果的0.4
		 */
		BigDecimal cpfqz;
		if (Constants.DEPT_TYPE_JQ.equals(result.getDeptType())) {
			cpfqz = round2(
						(
							round2(ldcpfpjz.multiply(new BigDecimal("0.4")))
							.add(round2(kscpfpjz.multiply(new BigDecimal("0.3"))))
							.add(round2(jqcpfpjz.multiply(new BigDecimal("0.3"))))
						).multiply(new BigDecimal("0.2"))
					);
		} else {
			cpfqz = round2(
						(
							round2(ldcpfpjz.multiply(new BigDecimal("0.4")))
							.add(round2(kscpfpjz.multiply(new BigDecimal("0.2"))))
							.add(round2(jqcpfpjz.multiply(new BigDecimal("0.4"))))
						).multiply(new BigDecimal("0.4"))
					);
		}
		result.setCpfqz(cpfqz);
	}
	
	/**
	 * 计算总得分
	 * @param result
	 */
	private void processTotal(Result result) {
		BigDecimal zdf = result.getJcfqz().add(result.getXckhqz()).add(result.getCpfqz());
		if (result.getZxkh() != null) {
			zdf = zdf.add(result.getZxkh());
		}
		if (result.getSzpy() != null) {
			zdf = zdf.add(result.getSzpy()); // 述职评议
		}
		result.setZdf(zdf);
		if (result.getSupfmqd() != null && result.getSupfmqd() > 0) {
			result.setZdf(ZERO);
		}
	}
	
	/**
	 * 计算排名
	 * @param monthId
	 */
	private void rank(String monthId) {
		Result _result = new Result();
		_result.setMonthId(monthId);
		List<Result> resultList = this.resultService.findList(_result);
		Collections.sort(resultList, new Comparator<Result>() {
			@Override
			public int compare(Result o1, Result o2) {
				return -(o1.getZdf().compareTo(o2.getZdf()));
			}
		});
		
		BigDecimal lastLwjgjqZdf = null;
		BigDecimal lastGnjqZdf = null;
		BigDecimal lastKsZdf = null;
		int lastLwjgjqIndex = 1;
		int lastGnjqIndex = 1;
		int lastKsIndex = 1;
		int lwjgjqIndex = 1;
		int gnjqIndex = 1;
		int ksIndex = 1;
		for (Result result : resultList) {
			if (Utils.notKhDept(result.getDept())) {
				result.setKhbz("N"); // 非考核部门
				continue;
			}
			
			result.setKhbz("Y");
			
			/**
			 * 劳务加工监区、功能监区单独排名
			 * 科室单独排名
			 */
			if (Utils.isJq(result.getDept())) {
				if (this.isScjq(result.getDept())) {
					if (lastLwjgjqZdf != null && lastLwjgjqZdf.compareTo(result.getZdf()) == 0) {
						result.setPm(lastLwjgjqIndex);
					} else {
						result.setPm(lwjgjqIndex);
					}
					lwjgjqIndex++;
					lastLwjgjqZdf = result.getZdf();
					lastLwjgjqIndex = result.getPm();
				} else {
					if (lastGnjqZdf != null && lastGnjqZdf.compareTo(result.getZdf()) == 0) {
						result.setPm(lastGnjqIndex);
					} else {
						result.setPm(gnjqIndex);
					}
					gnjqIndex++;
					lastGnjqZdf = result.getZdf();
					lastGnjqIndex = result.getPm();
				}
			} else {
				if (lastKsZdf != null && lastKsZdf.compareTo(result.getZdf()) == 0) {
					result.setPm(lastKsIndex);
				} else {
					result.setPm(ksIndex);
				}
				ksIndex++;
				lastKsZdf = result.getZdf();
				lastKsIndex = result.getPm();
			}
		}
		
		this.resultService.batchUpdateRank(resultList);
	}

	private boolean canCalc(String monthId) {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, -30);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
		if (df.format(c.getTime()).compareTo(monthId) < 0) {
			return false;
		}
		return true;
	}
	
	// 生产监区
	private boolean isScjq(Dept dept) {
		return !isGnjq(dept);
	}
	// 功能监区
	private boolean isGnjq(Dept dept) {
		return GNJQ.contains(dept.getDeptName());
	}
	// 科室分组1
//	private boolean isKsGroup1(Dept dept) {
//		return KS_GROUP1.contains(dept.getDeptName());
//	}
	
	/**
	 * 考核结果展示、导出时进行排序
	 * @param resultList
	 */
	private void orderResultList(List<Result> resultList) {
		// 暂定按照dept顺序排序
		return;
		
		/**
		List<Result> _noKh = new ArrayList<Result>();
		List<Result> jq = new ArrayList<Result>();
		List<Result> ks = new ArrayList<Result>();
		
		Iterator<Result> it = resultList.iterator();
		while (it.hasNext()) {
			Result _r = it.next();
			if (StringUtils.equals("N", _r.getKhbz())) {
				_noKh.add(_r);
			} else if (Utils.isJq(_r.getDept())) {
				jq.add(_r);
			} else {
				ks.add(_r);
			}
			
			it.remove();
		}
		
		Collections.sort(jq, new RankComparator());
		Collections.sort(ks, new RankComparator());
		Collections.sort(_noKh, new Comparator<Result>() {
			@Override
			public int compare(Result o1, Result o2) {
				if (o1 != null && o2 != null && o1.getZdf() != null && o2.getZdf() != null) {
					return o2.getZdf().compareTo(o1.getZdf());
				}
				return 0;
			}
		});

		// 设置颜色 begin
		for (Result r : jq) {
			r.setPmColor("1");
		}
		for (Result r : ks) {
			r.setPmColor("3");
		}
		// 设置颜色 end
		
		resultList.addAll(jq);
		resultList.addAll(ks);
		resultList.addAll(_noKh); // 将不参与考核的单位放到最后
		**/
	}
	
	/**
	 * 实际保留1位小数
	 * @param input
	 * @return
	 */
	private BigDecimal round2(BigDecimal input) {
		return input.divide(new BigDecimal("1"), 1, BigDecimal.ROUND_HALF_UP);
	}
	
	private String formatNumber(String input, boolean withPrefix) {
		if (StringUtils.isBlank(input)) {
			return "";
		}
		
		String v = input;
		while (v.contains(".") && v.endsWith("0")) {
			v = v.substring(0, v.length() - 1);
		}
		if (v.endsWith(".")) {
			v = v.substring(0, v.length() - 1);
		}
		
		if (withPrefix) {
			return "-" + v;
		}
		return v;
	}
	// 格式化数字显示
	private String formatNumber(BigDecimal input, boolean withPrefix) {
		if (input == null || input.compareTo(ZERO) == 0) {
			return "";
		}
		
		return this.formatNumber(input.toString(), withPrefix);
	}
	
	/**
	 * 设置excel格式的背景色
	 */
	private void setBgColor(CellStyle style, HSSFWorkbook wb, HSSFColorPredefined color, int r, int g, int b) {
		HSSFPalette palette = wb.getCustomPalette();
		palette.setColorAtIndex(color.getIndex(), (byte) r, (byte) g, (byte) b);
		style.setFillForegroundColor(color.getIndex());
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
	}
	
	/**
	 * 按照排名进行排序
	 * @author xuxiaoming 2023/03/17 14:32:28
	 */
	/**
	private class RankComparator implements Comparator<Result> {
		@Override
		public int compare(Result o1, Result o2) {
			if (o1 != null && o2 != null && o1.getPm() != null && o2.getPm() != null) {
				return o1.getPm().compareTo(o2.getPm());
			}
			return 0;
		}
	}
	**/
	
	/**
	private boolean disappearDept(Dept dept) {
		return DISAPPEAR_DEPT.contains(dept.getDeptName());
	}
	**/
}